package com.sf.dlb.config;

import com.sf.dlb.bean.NewRquestBean;
import com.sf.dlb.bean.VideoRquestBean;
import com.sf.dlb.jpa.model.TokenEntity;
import com.sf.dlb.jpa.model.UserInfo;
import com.sf.dlb.jpa.repository.UserInfoRepository;
import com.sf.dlb.mongo.model.NewList;
import com.sf.dlb.mongo.model.VideoList;
import com.sf.dlb.mongo.repository.NewListRepository;
import com.sf.dlb.mongo.repository.VideoListRepository;
import com.sf.dlb.utils.StateToValueUtils;
import com.sf.dlb.vo.ResultVO;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 日志收集AOP
 * Created by tanjing on 2019/6/4.
 */
@Aspect
@Component
public class LogAspect {
    private static final Logger logger= LoggerFactory.getLogger("bigdata");
    private static final Logger logger2= LoggerFactory.getLogger(LogAspect.class);

    @Autowired
    private UserInfoRepository userInfoRepository;
    @Autowired
    private NewListRepository newListRepository;
    @Autowired
    private VideoListRepository videoListRepository;

    /**
     * 切点
     */
//    @Pointcut("@annotation(com.sf.dlb.config.LogWeb)")
    @Pointcut("execution(public * com.sf.dlb.controller.*.*(..))")
    private void logPointcut(){};
    /**
     * 之前
     */
    @Before("logPointcut()")
    private void doBefore(JoinPoint joinPoint){
/*        日期 时间 用户 等级 设备 请求IP 操作 操作参数 附加参数
        操作；	 注册,阅读，充值，购买等；
        操作参数：阅读-热点/网易，播放-娱乐/影视等
        附加参数：预留信息*/
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request =attributes.getRequest();
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        String userAgent = request.getHeader("User-Agent");
        Object[] args=joinPoint.getArgs();
        if(null==resultVO){
            logger2.info("doBefore null==resultVO");
            return;
        }
        TokenEntity tokenEntity =(TokenEntity)resultVO.getData();
        if(null==tokenEntity){
            logger2.info("doBefore null==tokenEntity");
            return;
        }
        UserInfo userInfo=userInfoRepository.findByUserIdAndDelFlag(tokenEntity.getUserId(),"0");
        if(null==userInfo){
            logger2.info("doBefore null==userInfo");
            return;
        }
        if(null==args){
            logger2.info("doBefore null==args");
            return;
        }
        //收集的值
        String userId=tokenEntity.getUserId();
        String usergrade=userInfo.getUserGrade();
        String device= StateToValueUtils.switchRequestUserAgent(userAgent);
        String reqeustIp=request.getRemoteAddr();
        String handler=hanlderRquestUri(request.getRequestURI(),args);
        String handlerParameter= getRqeustArgs(request.getRequestURI(),args);//GsonUtils.getInstance().toJson(args);

        StringBuffer logStr=new StringBuffer();
        logStr.append(userId).append(" ");
        logStr.append(usergrade).append(" ");
        logStr.append(device).append(" ");
        logStr.append(reqeustIp).append(" ");
        logStr.append(handler).append(" ");
        logStr.append(handlerParameter).append(" ");
        logger.info(logStr.toString());

    }
    /**
     * 之后
     */
    @AfterReturning(returning = "ret",pointcut = "logPointcut()")
    private void doAfterReturning(Object ret){
    }

    /**
     * 处理请求URI
     */
    public String hanlderRquestUri(String uri,Object[] args){
        if(StringUtils.contains(uri,"/v1/new/read")){
            NewRquestBean newRquestBean=(NewRquestBean)args[1];
            if(StringUtils.isNotBlank(newRquestBean.getStartTime())){
                uri="/v1/new/read_start";
            }else if (StringUtils.isNotBlank(newRquestBean.getEndTime())){
                uri="/v1/new/read_end";
            }
        }else if(StringUtils.contains(uri,"/v1/video/play")){
            VideoRquestBean videoRquestBean=(VideoRquestBean)args[1];
            if(StringUtils.isNotBlank(videoRquestBean.getStartTime())){
                uri="/v1/video/play_start";
            }else if (StringUtils.isNotBlank(videoRquestBean.getEndTime())){
                uri="/v1/video/play_end";
            }
        }
        return uri;
    }
    /**
     * 获取请求参数
     */
    public String getRqeustArgs(String uri,Object[] args){
        String argsStr="";
        if(StringUtils.contains(uri,"/v1/new/read")){
            NewRquestBean newRquestBean=(NewRquestBean)args[1];
            String newId=newRquestBean.getNewId();
            NewList newList=newListRepository.findByIdAndDelFlag(newId,"0");
            argsStr=newList.getClassId();
        }else if(StringUtils.contains(uri,"/v1/video/play")){
            VideoRquestBean videoRquestBean=(VideoRquestBean)args[1];
            String videoId=videoRquestBean.getVideoId();
            VideoList videoList=videoListRepository.findByIdAndDelFlag(videoId,"0");
            String source=new String(Base64Utils.decodeFromString(videoList.getSource()));
            argsStr=source;
        }
        return argsStr;
    }
}

